package xcmg.device.service.basic;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.agent.ServiceBasicDataAgentDO;
import xcmg.device.dao.entity.basic.MaterialsSupplierDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.agent.ServiceBasicDataAgentMapper;
import xcmg.device.dao.mapper.basic.MaterialsSupplierMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.basic.MaterialsSupplierVO;
import xcmg.device.service.vo.company.CompanySupplierVO;
import xcmg.device.service.warehouse.CommonService;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class MaterialsSupplierService {


  @Autowired
  private MaterialsSupplierMapper materialsSupplierMapper;

  @Autowired
  private FastGenClient fastGenClient;

  @Autowired
  private CompanySupplierMapper companySupplierMapper;

  @Autowired
  private PriMaterialsMapper priMaterialsMapper;

  @Autowired
  private CommonService commonService;

  @Autowired
  private HttpServletResponse response;

  @Autowired
  private ServiceBasicDataAgentMapper agentMapper;

  @Value("${spring.file.download.path}")
  private String filePath;

  /**
   * excel模板文件名
   */
  private static final String MATERIALS_SUPPLIER_TEMPLATE_FILE = "MaterialsSupplier.xls";


  /**
   * 是否直投属性：0 非直投，1直投
   */
  private static final Integer IS_DIRECT_CAST_NO = 0;

  /**
   * 删除
   */
  public int remove(String id) {
    return materialsSupplierMapper.deleteByPrimaryKey(id);
  }

  /**
   * 新增
   */
  public int add(MaterialsSupplierVO materialsSupplierVO) throws Exception {

    if (StringUtils.isBlank(materialsSupplierVO.getMaterialsId())) {
      throw new Exception("零件主键不能为空");
    }
    if (StringUtils.isBlank(materialsSupplierVO.getSupplierCode())) {
      throw new Exception("供应商编码不能为空");
    }

    PriMaterialsDO materialsDO = priMaterialsMapper.item(materialsSupplierVO.getMaterialsId());
    if (null == materialsDO) {
      throw new Exception("零件不存在");

    }
    if (IS_DIRECT_CAST_NO.equals(materialsDO.getIsDirectCast())&&IS_DIRECT_CAST_NO.equals(materialsDO.getIsDirectCastHF())) {
      throw new Exception("该零件为非直投，不能添加供应商");
    }
    MaterialsSupplierDO materialsSupplierDO = new MaterialsSupplierDO();
    BeanUtils.copyProperties(materialsSupplierVO, materialsSupplierDO);
    materialsSupplierDO.setCreateTime(new Date());
    materialsSupplierDO.setId(fastGenClient.textGuid().getValue());

    CompanySupplierDO companySupplierDO = companySupplierMapper
        .itemByCode(materialsSupplierVO.getOrgId(), materialsSupplierVO.getSupplierCode());
    if (null == companySupplierDO) {
      throw new Exception("编码为" + materialsSupplierVO.getSupplierCode() + "供应商不存在");
    }
    if (IS_DIRECT_CAST_NO.equals(companySupplierDO.getIsDirect())&&IS_DIRECT_CAST_NO.equals(companySupplierDO.getIsDirectHF())) {
      throw new Exception("供应商" + materialsSupplierVO.getSupplierCode() + "非直投，不能添加");
    }
    if (!companySupplierDO.getIsPlatCompany()) {
      throw new Exception("供应商" + materialsSupplierVO.getSupplierCode() + "未上平台，不能添加");
    }
    materialsSupplierDO.setMaterialsNo(materialsDO.getMaterialsNo());
    materialsSupplierDO.setSupplierOrgId(companySupplierDO.getPlatOrgId());
    materialsSupplierDO.setSupplierComName(companySupplierDO.getCompanyName());
    try {
      return materialsSupplierMapper.insert(materialsSupplierDO);
    } catch (Exception e) {
      if (e instanceof DuplicateKeyException) {
        log.info("该记录已经存在,", e);
        throw new CommonBusiExceptions("该记录已经存在，请检查！");
      } else {
        log.info("新增异常,", e);
        throw new CommonBusiExceptions("新增产生异常:" + e.getMessage());
      }
    }
  }


  public PageCommonVO<MaterialsSupplierVO> list(SearchCommonVO<MaterialsSupplierVO> condition, String orgId) {

    PageCommonVO<MaterialsSupplierVO> result = new PageCommonVO<>();
      PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
    List<MaterialsSupplierDO> materialsSupplierDOS = materialsSupplierMapper.list(condition.getFilters());

    Map<String, String> salesInfo = getSalesInfo(orgId);

    List<MaterialsSupplierVO> voList = new ArrayList<>();
    if (CollectionUtils.isEmpty(materialsSupplierDOS)) {
      result.setPageInfo(new PageInfo(voList));
      result.setPageInfoList(voList);
      return result;
    }
    MaterialsSupplierVO materialsSupplierVO;
    for (MaterialsSupplierDO materialsSupplierDO : materialsSupplierDOS) {
      materialsSupplierVO = new MaterialsSupplierVO();
      BeanUtils.copyProperties(materialsSupplierDO, materialsSupplierVO);
      materialsSupplierVO.setSalesCodeDes(salesInfo.get(materialsSupplierVO.getSalesCode()));
      voList.add(materialsSupplierVO);
    }
    result.setPageInfo(new PageInfo(voList));
    result.setPageInfoList(voList);
    return result;
  }

  /**
   * 获取销售组织信息
   * @Author: lxf
   * @Date: 2022/10/14 15:02
   * @params: [orgId]
   * @return: java.util.Map<java.lang.String,java.lang.String>
   */
  public Map<String, String> getSalesInfo(String orgId){
    ServiceBasicDataAgentVO agentVO = new ServiceBasicDataAgentVO();
    agentVO.setOrgId(orgId);
    agentVO.setpCode("SALES_ORG");
    List<ServiceBasicDataAgentDO> agentDOS = agentMapper.queryList(agentVO);
    return agentDOS
            .stream()
            .collect(Collectors.toMap(ServiceBasicDataAgentDO::getCode, ServiceBasicDataAgentDO::getRemark));
  }


  @Transactional
  public FunctionResult importFormExcel(MultipartFile file, String orgId, String userId) throws Exception {
    FunctionResult result = new FunctionResult();
    //Workbook wb = WorkbookFactory.create(in);
    Workbook wb;//同时兼容Excel-2003及Excel-2007
    try {
      InputStream in = file.getInputStream();
      wb = new HSSFWorkbook(in);
    } catch (Exception ex) {
      // 解决read error异常
      // in = new FileInputStream(file);
      InputStream in = file.getInputStream();
      wb = new XSSFWorkbook(in);
    }
    Sheet sheet = wb.getSheetAt(0);
    int totalRow = sheet.getLastRowNum();
    if (totalRow < 2) {
      result.setCode(ErrorCode.IllegalArument);
      result.setValue("导入模板不正确");
      return result;
    }
    int totalCell = sheet.getRow(1).getLastCellNum();
    if (totalCell != 5) {
      result.setCode(ErrorCode.IllegalArument);
      result.setValue("导入模板不正确");
      return result;
    }
    List<MaterialsSupplierVO> errorDetailVOList = new ArrayList<>();
    MaterialsSupplierDO materialsSupplierDO;
    boolean success;
    for (int i = 2; i <= totalRow; i++) {
      //HSSFRow curRow=sheet.getRow(i);
      Row curRow = sheet.getRow(i);
      MaterialsSupplierVO detailVO = new MaterialsSupplierVO();
      if (curRow == null) {
        continue;
      }
      String materialsNo = getCellValue(curRow, 1);
      String supplierCode = getCellValue(curRow, 2);
      String salesCodeDes = getCellValue(curRow, 4);
      System.out.println("salesCode" + salesCodeDes);
      if (StringUtil.isNullOrEmpty(materialsNo) && StringUtil.isNullOrEmpty(supplierCode) && StringUtil.isNullOrEmpty(salesCodeDes)) {
        break;
      }
      if (StringUtil.isNullOrEmpty(materialsNo)) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("零件编码不能为空");
        errorDetailVOList.add(detailVO);
        continue;
      }
      if (StringUtil.isNullOrEmpty(supplierCode)) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("供应商编码不能为空");
        errorDetailVOList.add(detailVO);
        continue;
      }
      if (StringUtil.isNullOrEmpty(salesCodeDes)) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("销售组织不能为空");
        errorDetailVOList.add(detailVO);
        continue;
      }
      PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
      if (priMaterialsDO == null) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("零件不存在，" + materialsNo);
        errorDetailVOList.add(detailVO);
        continue;
      }
      if (IS_DIRECT_CAST_NO.equals(priMaterialsDO.getIsDirectCast())&&IS_DIRECT_CAST_NO.equals(priMaterialsDO.getIsDirectCastHF())) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("该零件为非直投，不能添加供应商，" + materialsNo);
        errorDetailVOList.add(detailVO);
        continue;
      }
      CompanySupplierDO companySupplierDO = companySupplierMapper.itemByCode(orgId, supplierCode);
      if (null == companySupplierDO) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("供应商不存在，" + supplierCode);
        errorDetailVOList.add(detailVO);
        continue;
      }

      if (!companySupplierDO.getIsPlatCompany()) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("供应商不是平台企业，" + supplierCode);
        errorDetailVOList.add(detailVO);
        continue;
      }

      if (IS_DIRECT_CAST_NO.equals(companySupplierDO.getIsDirect())&&IS_DIRECT_CAST_NO.equals(companySupplierDO.getIsDirectHF())) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("供应商" + supplierCode + "非直投，不能添加");
        errorDetailVOList.add(detailVO);
        continue;
      }

      materialsSupplierDO = materialsSupplierMapper.getByMaterialsIdAndSupplierCode(priMaterialsDO.getMaterialsId(), supplierCode);
      if (null != materialsSupplierDO) {
        continue;
      }

      ServiceBasicDataAgentDO agentDO = agentMapper.selectByRemark(salesCodeDes, orgId);
      if (ObjectUtils.isEmpty(agentDO)) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("销售组织不存在，" + salesCodeDes);
        errorDetailVOList.add(detailVO);
        continue;
      }


      materialsSupplierDO = new MaterialsSupplierDO();
      materialsSupplierDO.setId(fastGenClient.textGuid().getValue());
      materialsSupplierDO.setMaterialsId(priMaterialsDO.getMaterialsId());
      materialsSupplierDO.setOrgId(priMaterialsDO.getOrgId());
      materialsSupplierDO.setMaterialsNo(priMaterialsDO.getMaterialsNo());
      materialsSupplierDO.setSupplierOrgId(companySupplierDO.getPlatOrgId());
      materialsSupplierDO.setSupplierCode(supplierCode);
      materialsSupplierDO.setSupplierComName(companySupplierDO.getCompanyName());
      materialsSupplierDO.setCreateId(userId);
      materialsSupplierDO.setCreateName(commonService.getUserName(userId));
      materialsSupplierDO.setCreateTime(new Date());
      materialsSupplierDO.setSalesCode(agentDO.getCode());
      success = materialsSupplierMapper.insert(materialsSupplierDO) > 0;
      if (!success) {
        detailVO.setErrorRow(i + 1);
        detailVO.setRemark("新增失败，" + priMaterialsDO.getMaterialsNo());
        errorDetailVOList.add(detailVO);
        continue;
      }
    }

    if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
      result.setValue(new ArrayList<>());
      result.setCode(ErrorCode.Success);
    } else {
      result.setValue(errorDetailVOList);
      result.setCode(ErrorCode.IllegalArument);
    }
    return result;
  }

  private String getCellValue(Row curRow, int i) {
    String value = "";
    if (curRow.getCell(i) != null) {
      curRow.getCell(i).setCellType(CellType.STRING);
      value = curRow.getCell(i).getStringCellValue();
    }
    return value;
  }

  /**
   * 下载零件批量导入供应商的模板
   */
  public void download() throws Exception {
    FileUtil.downLoadFile(response, filePath, MATERIALS_SUPPLIER_TEMPLATE_FILE);
  }

  public PageCommonVO<CompanySupplierVO> listSuppliers(SearchCommonVO<MaterialsSupplierVO> searchVO) {
    PageCommonVO<CompanySupplierVO> result = new PageCommonVO<>();
      PageHelperPlus.startPage(searchVO.getPageNum(), searchVO.getPageSize());
    MaterialsSupplierVO materialsSupplierVO = searchVO.getFilters();
    List<CompanySupplierDO> companySupplierDOS = companySupplierMapper
        .list4MaterialsSupplier(materialsSupplierVO);
    List<CompanySupplierVO> supplierVOS = new ArrayList<>();

    if (CollectionUtils.isEmpty(companySupplierDOS)) {
      result.setPageInfo(new PageInfo(companySupplierDOS));
      result.setPageInfoList(supplierVOS);
      return result;
    }

    Map<String, String> salesInfo = getSalesInfo(materialsSupplierVO.getOrgId());
    CompanySupplierVO supplierVO;
    for (CompanySupplierDO supplierDO : companySupplierDOS) {
      supplierVO = new CompanySupplierVO();
      BeanUtils.copyProperties(supplierDO, supplierVO);
      supplierVO.setSalesCode(materialsSupplierVO.getSalesCode());
      supplierVO.setSalesCodeDes(salesInfo.get(materialsSupplierVO.getSalesCode()));
      supplierVOS.add(supplierVO);
    }
    result.setPageInfo(new PageInfo(companySupplierDOS));
    result.setPageInfoList(supplierVOS);
    return result;
  }

}
